﻿using Avalonia.Collections;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Tmds.DBus.Protocol;

namespace 畜牧业审核程序国产.Models.RagModel
{
    internal class ApiService
    {
        //private static readonly HttpClient _httpClient = new HttpClient();

        //// 假设API URL和相关参数
        //private const string ApiUrl = "https://api.example.com/endpoint"; // 替换为通义千问的实际API URL

        //public async Task<string> SendMessageAsync(string userMessage)
        //{
        //    // 创建请求内容
        //    var content = new StringContent(JsonConvert.SerializeObject(new { query = userMessage }), Encoding.UTF8, "application/json");

        //    // 发送请求
        //    var response = await _httpClient.PostAsync(ApiUrl, content);

        //    // 处理返回结果
        //    if (response.IsSuccessStatusCode)
        //    {
        //        var result = await response.Content.ReadAsStringAsync();
        //        // 假设返回的结果是纯文本
        //        return result;
        //    }

        //    return "Error: Unable to fetch data from API.";
        //}

        private static readonly HttpClient _httpClient = new HttpClient();
        private static string _apiKey = "sk-4487d1c2764d4c388af7a241ed28c7f4"; // 可替换为其他 API 密钥
        private static string _apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 请求URL



        public static async Task<string> SendRequestAsync(string prompt)
        {
            try
            {
                //var content = new StringContent(JsonConvert.SerializeObject(new { query = userMessage }), Encoding.UTF8, "application/json");
                //using (var client = new HttpClient())
                //{
                //    var requestContent = new
                //    {
                //        message = prompt,
                //        session_id = _sessionId
                //    };
                //}


                var content = new StringContent(
                    JsonSerializer.Serialize(new { prompt }),
                    System.Text.Encoding.UTF8,
                    "application/json");

                _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");

                HttpResponseMessage response = await _httpClient.PostAsync(_apiUrl, content);
                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();
                var jsonResponse = JsonSerializer.Deserialize<JsonElement>(responseBody);

                // 一般 API 返回的是 JSON 格式，且包含 "choices" 字段，每个 choice 包含 "text"
                var choices = jsonResponse.GetProperty("choices").EnumerateArray();
                var result = string.Join("\n", choices.Select(choice => choice.GetProperty("text").GetString()));

                return result;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 请求出错的话返回去"请求失败:"+错误说明
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonContent"></param>
        /// <param name="apiKey"></param>
        /// <returns></returns>
        public static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
        {
            try
            {
                using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
                {
                    // 设置请求头
                    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                    _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // 发送请求并获取响应
                    HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();//检查 HTTP 响应的状态码，并确保它是成功的状态（即200-299范围内的状态码响应的状态码表示成功，则该方法不会做任何事情，只是简单地返回响应对象本身。但如果响应状态码指示了一个错误（例如4xx客户端错误或5xx服务器错误），那么这个方法将会抛出一个 HttpRequestException 异常
                    // 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        return $"请求失败: {response.StatusCode}";
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
